#!/bin/bash
#!/bin/bash

# 颜色设置
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 恢复默认颜色

# 测试配置
ITERATIONS=10
TEST_STAGES=("2A" "2B" "2C")
OUTPUT_DIR="test_results"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# 创建结果目录
mkdir -p "$OUTPUT_DIR/$TIMESTAMP"

# 运行指定阶段的测试
run_stage_tests() {
    local stage=$1
    local results_file="$OUTPUT_DIR/$TIMESTAMP/results_${stage}.log"
    local failed=0

    echo -e "${YELLOW}========= RUNNING STAGE ${stage} TESTS ========${NC}"
    echo "Stage ${stage} Results (Iterations: $ITERATIONS)" > "$results_file"

    for i in $(seq 1 $ITERATIONS); do
        echo -e "\n${YELLOW}=== STAGE ${stage} ITERATION $i ===${NC}"
        echo -e "\n=== ITERATION $i ===" >> "$results_file"

        # 运行包含阶段标记的所有测试（如 Test2A、TestBasicElection2A 等）
        go test -race -run "$stage" . >> "$results_file" 2>&1
        TEST_STATUS=$?

        if [ $TEST_STATUS -ne 0 ]; then
            echo -e "${RED}❌ Stage ${stage} failed at iteration $i${NC}"
            echo -e "❌ Failed at iteration $i" >> "$results_file"
            failed=1
            break
        else
            echo -e "${GREEN}✅ Stage ${stage} iteration $i passed${NC}"
        fi
    done

    if [ $failed -eq 0 ]; then
        echo -e "${GREEN}🎉 All $ITERATIONS iterations of stage ${stage} passed!${NC}"
    else
        echo -e "${RED}🛑 One or more tests failed in stage ${stage}!${NC}"
        return 1
    fi
}

# 依次运行所有阶段的测试
all_passed=0
for stage in "${TEST_STAGES[@]}"; do
    run_stage_tests "$stage"
    if [ $? -ne 0 ]; then
        all_passed=1
    fi
done

# 输出汇总结果
echo -e "\n${YELLOW}========= TEST SUMMARY ========${NC}"
if [ $all_passed -eq 0 ]; then
    echo -e "${GREEN}✅ All stages (${TEST_STAGES[*]}) passed all iterations!${NC}"
else
    echo -e "${RED}❌ Some tests failed. Check logs in $OUTPUT_DIR/$TIMESTAMP${NC}"
fi

echo -e "\nDetailed results saved to: ${OUTPUT_DIR}/${TIMESTAMP}/"